package com.tangdi.production.mpaychl.service.impl.finance;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tangdi.production.mpaychl.base.service.BaseTranService;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.TranException;
import com.tangdi.production.mpbase.util.HttpUtil;
import com.tangdi.production.mpbase.util.MapUtils;
import com.tangdi.production.mpbase.util.MoneyUtils;
import com.tangdi.production.mpbase.util.ObjectUtil;
import com.tangdi.production.tdbase.util.MD5Util;

@Service("FinanceService")
public class FinanceServiceImpl implements BaseTranService{

	private static final Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);
	
	private static final String FINANCE_SERVER_URL = "http://finance-pay.com/api/payment.shtml";

	private static final String	MERCH_ID = "30013";
	
	public static final String SIGNKEY = "0ada5b8118a74f5f8e9e309f22500f0c";
	
	private static final String NOTIFY_URL = "http://ce.imbitpay.com:8083/mpcctp/finance/notify-url.json";
	
	@Override
	public Map<String, Object> execute(Map<String, Object> params) throws TranException {
		logger.info("进入FinanceService处理接口 [{}]", params);

		String prdordno = "" + params.get("prdordno");
		String payAmt = ObjectUtil.getString(params.get("payAmt"));
		logger.info("支付金额[{}分]", payAmt);
		payAmt = MoneyUtils.toStrYuan(payAmt);
		logger.info("支付金额转换为元[{}]", payAmt);
		String payBank = (String) (params.get("payBank") == null ? "CMBcmb103_DEPOSIT_DEBIT_EBANK_XBOX_MODEL" : params.get("payBank"));
		
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("version", "0.1");
			paramMap.put("merchID", MERCH_ID);	// 商户号
			paramMap.put("money", payAmt);				// 支付总额，单位元
			paramMap.put("orderno", prdordno);			// 商户订单号
			paramMap.put("syncurl", NOTIFY_URL);
		    
			paramMap.put("sign", sign(paramMap, SIGNKEY));
			System.out.println("url:" + FINANCE_SERVER_URL);

			StringBuilder returtnHtml = new StringBuilder();
			returtnHtml.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" /></head><body><script language=\"javascript\">window.onload=function(){document.payfrm.submit();}</script>");
			returtnHtml.append("<form id=\"payfrm\" name=\"payfrm\" action=\"").append("http://ce.imbitpay.com/gateway").append("\" method=\"post\" >");
			returtnHtml.append("<input type=\"hidden\" name=\"version\" value=\"").append("0.1").append("\" />");
			returtnHtml.append("<input type=\"hidden\" name=\"merchID\" value=\"").append(MERCH_ID).append("\" />");
			returtnHtml.append("<input type=\"hidden\" name=\"money\" value=\"").append(payAmt).append("\" />");
			returtnHtml.append("<input type=\"hidden\" name=\"orderno\" value=\"").append(prdordno).append("\" />");
			returtnHtml.append("<input type=\"hidden\" name=\"syncurl\" value=\"").append(NOTIFY_URL).append("\" />");
			returtnHtml.append("<input type=\"hidden\" name=\"sign\" value=\"").append(paramMap.get("sign")).append("\" />");
			returtnHtml.append("</form></body></html>");
			
			Map<String,Object> backMap = new HashMap<>();
			backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			backMap.put("contentType", MsgCT.DATA_TYPE_HTML);
			backMap.put("busContent", returtnHtml.toString());
			return backMap;
		} catch (Exception e) {
			logger.error("渠道FinanceService调用异常:{}", e.getMessage(), e);
			Map<String,Object> backMap = new HashMap<>();
			backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
			backMap.put("msg", String.format("渠道调用异常:%s" , e.getMessage()));
			return backMap;
		}
	}

	private static String 
	sign(Map<String, Object> paramMap, String signKey) {
		String signStr = MapUtils.getSignStrByTreeMap(paramMap, true);
		signStr += "&key=" + signKey;
		// String signValue = MD5.encryption(signStr).toUpperCase();
		String signValue = MD5Util.digest(signStr).toUpperCase();
		return signValue;
	}
	
	public static void main(String[] args) {
		
		FinanceServiceImpl ePay = new FinanceServiceImpl();
		
		Map<String, Object> param = new HashMap<>();
		param.put("payAmt", 1.12);
		param.put("prdordno", System.currentTimeMillis() + RandomStringUtils.randomAlphabetic(5));
		param.put("payBank", "CMBcmb103_DEPOSIT_DEBIT_EBANK_XBOX_MODEL");
		
		try {
			ePay.execute(param);
		} catch (TranException e) {
			e.printStackTrace();
		}
	}
	
}
